package com.hsav.kcxb.fragment.sing;

import android.app.Fragment;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.hsav.kcxb.R;

import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link PlayListFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link PlayListFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class PlayListFragment extends Fragment implements View.OnClickListener, AdapterView.OnItemClickListener {

    static interface SingleSelectItem
    {
        boolean isSelected();
    }

    static class PlaylistItem implements SingleSelectItem
    {
        private boolean selected;

        @Override
        public boolean isSelected() {
            return selected;
        }

        public void setSelected(boolean isSelected)
        {
            selected = isSelected;
        }
    }

    static class PlayListAdapter extends BaseAdapter
    {
        private final Context context;
        private LayoutInflater layoutInflater;
        private List<PlaylistItem> data;

        public PlayListAdapter(Context context)
        {
            this.context = context;
            layoutInflater = LayoutInflater.from(context);
            data = new ArrayList<>();
        }

        public PlayListAdapter(Context context, List<PlaylistItem> data)
        {
            this.context = context;
            if (data == null)
                this.data = new ArrayList<>();
            else
                this.data = new ArrayList<>(data);
            layoutInflater = LayoutInflater.from(context);
        }

        public void setData(List<PlaylistItem> data)
        {
            this.data.clear();
            if (data == null) return;
            this.data.addAll(data);
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return data.size();
        }

        @Override
        public Object getItem(int position) {
            return data.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder;
            if (convertView == null)
            {
                convertView = layoutInflater.inflate(R.layout.item_play_list, parent, false);
                viewHolder = new ViewHolder();
                viewHolder.textNumber = (TextView) convertView.findViewById(R.id.text_number);
                viewHolder.textSingerName = (TextView) convertView.findViewById(R.id.text_singer_name);
                viewHolder.textSongName = (TextView) convertView.findViewById(R.id.text_song_name);
                viewHolder.imgLogo = (ImageView) convertView.findViewById(R.id.img_logo);
                convertView.setTag(viewHolder);
            }
            else
            {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            // TODO: 2017/6/24
            PlaylistItem item = data.get(position);
            viewHolder.textNumber.setText("1");
            viewHolder.textNumber.setVisibility(item.isSelected() ? View.INVISIBLE : View.VISIBLE);
            viewHolder.imgLogo.setImageResource(R.drawable.head);
            viewHolder.imgLogo.setVisibility(item.isSelected() ? View.VISIBLE : View.INVISIBLE);
            viewHolder.textSingerName.setText("刘德华");
            viewHolder.textSongName.setText("爱你一万年");
            return convertView;
        }

        static class ViewHolder
        {
            public TextView textNumber;
            public TextView textSongName;
            public TextView textSingerName;
            public ImageView imgLogo;
        }
    }
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;
    private TextView textTitle;
    private ListView listPlay;
    private PlayListAdapter adapter;
    private PlaylistItem lastSelectedItem;

    public PlayListFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment PlayListFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static PlayListFragment newInstance(String param1, String param2) {
        PlayListFragment fragment = new PlayListFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_play_list, container, false);
        textTitle = (TextView)rootView.findViewById(R.id.text_title);
        textTitle.setText("播发列表 80");
        ImageView imgAdd = (ImageView) rootView.findViewById(R.id.img_add);
        imgAdd.setOnClickListener(this);
        ImageView imgOrder = (ImageView) rootView.findViewById(R.id.img_order);
        imgOrder.setOnClickListener(this);
        listPlay = (ListView)rootView.findViewById(R.id.list_songs);
        listPlay.setOnItemClickListener(this);
        adapter = new PlayListAdapter(getActivity());
        listPlay.setAdapter(adapter);
        //测试用
        CreateTestData();
        FrameLayout fameRoot = (FrameLayout) rootView.findViewById(R.id.frame_root);
        fameRoot.setOnClickListener(this);
        return rootView;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        PlaylistItem item = (PlaylistItem) adapter.getItem(position);
        if (lastSelectedItem != null)
        {
            lastSelectedItem.setSelected(false);
        }
        item.setSelected(true);
        lastSelectedItem = item;
        adapter.notifyDataSetChanged();
        Toast.makeText(getActivity(), String.format("用户点击了第%s首歌曲", position), Toast.LENGTH_SHORT).show();
    }

    private void CreateTestData()
    {
        List<PlaylistItem> data = new ArrayList<>(10);
        for (int i = 0; i < 10; i++)
        {
            data.add(new PlaylistItem());
        }
        adapter.setData(data);
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId())
        {
            case R.id.img_add:
                Toast.makeText(getActivity(), "添加歌曲按钮被点击了", Toast.LENGTH_SHORT).show();
                break;
            case R.id.img_order:
                Toast.makeText(getActivity(), "播发顺序按钮被点击了", Toast.LENGTH_SHORT).show();
                break;
            case R.id.frame_root:
                if (mListener != null)
                {
                    mListener.onRequestClose(this);
                }
                break;
        }
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onRequestClose(Fragment sender);
    }
}
